define(backboneCommon.getViewDefine("adspace.index"), function ($,require,Collection,tpl) {
    var backboneView= Backbone.View.extend({
        el: "#container_body",
        events: {
            "keydown #search_keyword": "enterKeyword",
            "click #btn_search": "refreshList",
            'click #tb_listAdSpace .adspace-delete': 'deleteAdSpace'
        },
        initialize: function () {
            this.modelAttach={};
            this.modelAttach.baseData=this.model.get("modelBaseData");
            this.modelAttach.media=this.model.get("modelMedia");
            this.listenTo(this.modelAttach.baseData, 'bind:AdFormat', this.bindAdFormat);
            this.listenTo(this.modelAttach.baseData, 'bind:Os', this.bindOs);
            this.listenTo(this.modelAttach.media, 'bind:DropDownMedia', this.bindMedia);
            this.listenTo(this.model, 'bind:PageList', this.bindList);
            this.listenTo(this.model, 'save:Delete', this.deleteAdSpaceCallback);
            this.listenTo(this.model, 'update:Status', this.updStatusCallback);
            this.render();
        },
        render:function(json){
            var templateHtml=_.template(tpl);
            this.$el.html(templateHtml(json));
        },
        initMain:function(){
            this.elementModel={};
            this.extObject={};
            this.pageData={};
            this.elementModel.table=$("#tb_listAdSpace");
            this.pageData.operateStatus=this.model.get("defListStatus");
            this.pageData.option=this.modelAttach.baseData.get("defSelectOption");
            this._bindStatus();
            this._initPageList();
        },
        bindAdFormat:function () {
            var self=this;
            var res=this.modelAttach.baseData.get("dataListAdFormat");
            $("#search_adformat").ExtSelect2({placeholder: "-形式-", infoExt:{defaultValue:self.pageData.option, data:res.data,
                changeCallback:function(){self.refreshList()}
            }});
            if(!res.success){ $.ExtNotify.error("形式数据获取失败："+res.msg);}
        },
        bindOs:function () {
            var self=this;
            var res=this.modelAttach.baseData.get("dataListOs");
            $("#search_os").ExtSelect2({placeholder: "-操作系统-",infoExt:{data:res.data,defaultValue:self.pageData.option,
                changeCallback:function(){self.refreshList()}
            }});
            if(!res.success){ $.ExtNotify.error("操作系统数据获取失败："+res.msg);}
        },
        bindMedia:function () {
            var self=this;
            var res=this.modelAttach.media.get("dataDropDownMedia");
            $("#search_media").ExtSelect2({placeholder: "-媒体-", minimumResultsForSearch: 1, infoExt:{data:res.data,defaultValue:self.pageData.option,
                changeCallback:function(){self.refreshList()}
            }});
            if(!res.success){ $.ExtNotify.error("媒体系统数据获取失败："+res.msg);}
        },
        _bindStatus:function () {
            var self=this;
            var list=$.ExtCommon.convertListByPara(self.pageData.operateStatus);
            $("#search_status").ExtSelect2({placeholder:"-状态-",infoExt:{data: list,defaultValue:self.pageData.option,
                changeCallback:function(){self.refreshList()}
            }});
        },
        _initPageList: function () {
            var self=this;
            self.extObject.table=self.elementModel.table.ExtDataTable({
                columns: [
                    {"data": "id", sClass: "w-60"},
                    {"data": "name",sClass: "p-r-20"},
                    {"data": "statusName",sClass: "w-60 text-center"},
                    {"data": "formatName", sClass: "w-80 text-center"},
                    {"data": "osName",sClass: "w-100"},
                    {"data": null, sClass: "w-200"},
                    {"data": "pubSiteName", sClass: "w-140"}
                ],
                infoExt:{
                    ajaxDataPara:function(){
                        var param= $.ExtAssist.initParamExt();
                        var keyword = $.trim($("#search_keyword").val());
                        if (!$.ExtCommon.isCheckEmpty(keyword)) {param.search = keyword;}
                        var media = $("#search_media").val();
                        if (!$.ExtCommon.isCheckEmpty(media,"-99")) {param.media = media;}
                        var adformat = $("#search_adformat").val();
                        if (!$.ExtCommon.isCheckEmpty(adformat,"-99")) {param.adformat = adformat;}
                        var status = $("#search_status").val();
                        if (!$.ExtCommon.isCheckEmpty(status,"-99")) {param.status = status;}
                        var os = $("#search_os").val();
                        if (!$.ExtCommon.isCheckEmpty(os,"-99")) {param.os = os;}
                        return param;
                    },
                    ajaxWholeCallback:function(param){
                        self.collection.getPageList(param)
                    }
                },
                createdRow: function (row, data) {
                    var elementTd=$('td', row);
                    elementTd.eq(1).attr("id","adspace_"+data.id).html($("#template_adSpaceName").render({name: data.name, id: data.id}));
                    var josnOperateStatus = self._bindTableColumnByStatus(data.status);
                    elementTd.eq(2).html('<a class="editable editable-click editable-init btn-operate"  data-operatetype="status" href="javascript:;">' + data.statusName + '</a>');
                    elementTd.eq(2).find(".editable").data({list: josnOperateStatus.list, id: data.id});
                    var template=data.formatId=="5"?$.ExtCommon.getStringConnect("{0} - {1}",[data.templateId,data.templateName]):data.ratioValue;
                    elementTd.eq(5).html($.ExtCommon.getStringConnect('<div class="ellipsis-txt-title w-200" title="{0}">{0}</div>',[template]));
                    elementTd.eq(6).html($.ExtCommon.getStringConnect('<div class="ellipsis-txt-title w-140" title="{0}">{0}</div>',[data.pubSiteName]));
                },
                drawCallback: function () {
                    self._initXEditable();
                }
            });
        },
        bindList:function(){
            var data=this.model.get("dataPageList");
            this.extObject.table.ajaxWholeRefreshData(data);
        },
        refreshList: function () {this.extObject.table.refresh();},
        enterKeyword:function(e){if(e.keyCode == 13) {this.refreshList();}},
        _bindTableColumnByStatus: function (status) {
            status=status==null?"":status.toString();
            var list=$.map(this.pageData.operateStatus,function (info) {
                if(info.showIds.indexOf(status)>-1){
                    return {value:info.id,text:info.text}
                }
            });
            return {status: status, list: list}
        },
        _initXEditable: function () {
            var self=this;
            self.elementModel.table.find(".editable-init").each(function () {
                var _this = $(this);
                _this.removeClass("editable-init");
                var _thisData = _this.data();
                var row =self.extObject.table.getRowInfo(_this.parents('tr:first'));
                var rowData=row.data();
                var id=rowData.id.toString();
                var operatetype =_thisData["operatetype"];
                if (operatetype == "status") {
                    _this.ExtXEditable({
                        source: _thisData.list,
                        type: "select",
                        params: function (params) {
                            var newParams= $.ExtAssist.initParamExt();
                            newParams.id=id;
                            newParams.status=$.trim(params.value);
                            return JSON.stringify(newParams);
                        },
                        infoExt:{
                            initControlOther: function () {
                                _this.siblings(".editable-container").find("select").ExtSelect2({infoExt: {initvalue: _thisData.list[0].value}});
                            },
                            ajaxWholeCallback:function (param,cb) {
                                $.ExtNotify.destroy();
                                self.collection.updateStatus(param);
                                self.xEditableStatusCallback=cb;
                            },
                            successCallback: function (res, newValue) {
                                var josnOperateStatus = self._bindTableColumnByStatus(newValue);
                                _this.text(res.data.statusName).data("list", josnOperateStatus.list);
                                _this.ExtXEditable().refresh(josnOperateStatus.list);
                                row.data().status = newValue;
                            }
                        }
                    });
                }
            });
        },
        updStatusCallback:function () {
            var result=this.model.get("dataUpdStatus");
            this.xEditableStatusCallback(result.res);
        },
        deleteAdSpace:function(e){
            var self=this;
            var tr=$(e.currentTarget).parents('tr:first');
            var trData =self.extObject.table.getRowInfo(tr).data();
            var id=trData.id;
            $.ExtSweetAlert.confirmSimple("您确定要删除该数据吗？",trData.name,function () {
                self.collection.operateDelete(id);
            });
        },
        deleteAdSpaceCallback:function(){
            $.ExtNotify.destroy();
            var res = this.model.get('dataDelete');
            if (res.success) {
                $.ExtNotify.success("删除成功");
                this.refreshList();
            }else{
                $.ExtNotify.error(res.msg);
            }
            $.ExtSweetAlert.checkClose(res.success);
        }
    });
    var viewModel=function(){
        this.collection= new Collection();
        this.model=this.collection.model;
        this.view=new backboneView({collection:this.collection,model:this.model});
        this.view.initMain();
    };
    viewModel.prototype={};
    return viewModel;
});